package com.zzx.filter;

import com.zzx.domain.LoginUser;
import com.zzx.exception.ExceptionState;
import com.zzx.exception.SystemException;
import com.zzx.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.net.www.protocol.http.AuthenticationHeader;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
@Component
public class SecurityFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 判断请求是否携带token
        String token = request.getHeader("Authorization");
        // 判断token是否为空
        if(Objects.isNull(token)||"null".equals(token) || request.getRequestURI()=="/user/login") {
            filterChain.doFilter(request,response);
            return;
        }
        // 解析token 判断token是否合法
        String id;
        try {
            Claims claims = JwtUtil.parseJWT(token);
             id = claims.getSubject();
        } catch (Exception e) {
            throw new SystemException("token不合法");
        }
        // 从redis中查询token 判断用户是否登录
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("manage-" + id);
        if(loginUser==null) throw new SystemException(ExceptionState.UNLOGINUSERNSME);
        // 将从redis中查询出来的值保存到本次请求中让其他过滤器共同使用
        /*设置全局可用*/
        UsernamePasswordAuthenticationToken passwordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(passwordAuthenticationToken);
        filterChain.doFilter(request,response);
    }
}
